/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package view.contents.transition;

import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.swing.Timer;

import view.contents.ImageTransitioner;
import config.Helper;

/**
 * 
 * @author Yang Wang <yang@digitalmenubox.com>
 */
public class WipeLeft implements ImageTransition, ActionListener {

	private ImageTransitioner box;
	private BufferedImage bi;
	private Graphics2D g;
	private double widthRatio = 0;
	private Timer timer;
	private boolean finished;

	public WipeLeft(ImageTransitioner box) {
		this.box = box;
		bi = new BufferedImage(box.getWidth(), box.getHeight(), BufferedImage.TYPE_INT_ARGB);
		g = (Graphics2D) bi.getGraphics();
		widthRatio = 0;
	}

	@Override
	public void animate(ImageTransitioner box, int time) {
		timer = new Timer(20, this);
		timer.setDelay(20);
		timer.start();
		// make the timer wait until the animation has been finished
		synchronized (timer) {
			try {
				timer.wait();
			} catch (InterruptedException ex) {
				Logger.getLogger(SlideDown.class.getName()).log(Level.SEVERE, null, ex);
			}
		}
	}

	public static void main(String[] args) {
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		if (widthRatio <= 1) {
			g.setClip(box.getWidth() - (int) (widthRatio * box.getWidth()), 0, box.getWidth(), box.getHeight());
			g.drawImage(box.getOverlayImage(), 0, 0, null);
			widthRatio = Helper.numberToPrecision(widthRatio + 0.05, 2);
			box.setTransitionImage(bi);
		} else {
			synchronized (timer) {
				timer.stop();
				timer.notifyAll();
				this.unsetVariables();
			}
		}
	}

	private void unsetVariables() {
		this.box = null;
		bi = null;
		g = null;
	}
}
